<template>
  <div class="mobile-page">
    <!-- 头部 -->
    <div class="header">
      <h1>移动端菜单</h1>
    </div>

    <!-- 菜单容器 -->
    <div class="menu-container">
      <!-- 一级菜单 -->
      <div
          v-for="(menu, index) in processedMenuList"
          :key="menu.docId"
          class="menu-item"
      >
        <!-- 一级菜单项 -->
        <div
            class="menu-level-1"
            :class="{ 'active': selectedMenu === index }"
            @click="toggleMenu(index)"
        >
          <div class="menu-content">
            <i class="el-icon-folder menu-icon"></i>
            <span class="menu-title">{{ menu.title }}</span>
          </div>
          <i class="el-icon-arrow-down arrow-icon" :class="{ 'rotated': menu.expanded }"></i>
        </div>

        <!-- 二级菜单 -->
        <transition name="submenu">
          <div v-show="menu.expanded" class="submenu">
            <div
                v-for="(subItem, subIndex) in menu.children"
                :key="subItem.cataLogId"
                class="menu-level-2"
                :class="{ 'active': selectedSubMenu === subItem.cataLogId }"
                @click="selectSubMenu(subItem)"
            >
              <i class="el-icon-document submenu-icon"></i>
              <span class="submenu-title">{{ subItem.title }}</span>
            </div>
          </div>
        </transition>
      </div>
    </div>

    <!-- PDF预览区域 -->
    <div class="pdf-container" v-if="showPdf">
      <div class="pdf-header">
        <h3>{{ currentSubMenu.title }}</h3>
        <button class="close-btn" @click="closePdf">
          <i class="el-icon-close"></i>
        </button>
      </div>
      <div class="pdf-content">
        <div v-if="loading" class="loading">
          <i class="el-icon-loading"></i>
          <p>正在加载PDF...</p>
        </div>
        <div v-else-if="pdfError" class="error">
          <i class="el-icon-warning"></i>
          <p>{{ pdfError }}</p>
          <button @click="loadPdf" class="retry-btn">重试</button>
        </div>
        <div v-else class="pdf-viewer">
<!--          <iframe
              v-if="pdfUrl"
              :src="pdfUrl"
              width="100%"
              height="100%"
              frameborder="0"
          ></iframe>-->

<!--          <object
              v-if="pdfUrl"
              :data="pdfUrl"
              type="application/pdf"
              width="100%"
              height="100%"
              class="pdf-object"
          >
            <p>您的浏览器不支直接PDF预览，请 <a :href="pdfUrl" target="_blank">点击此处预览</a></p>
          </object>-->

<!--          <iframe
              :src="pdfUrl"
              width="100%"
              height="100%"
              frameborder="0"
              sandbox="allow-same-origin allow-scripts allow-forms allow-popups"
              @load="onPdfLoad"
              @error="onPdfError"
          ></iframe>-->


<!--          <embed
              :src="pdfUrl"
              type="application/pdf"
              width="100%"
              height="100%"
          />-->

<!--          <pdf  :src="pdfUrl"  />-->

          <!-- base64方式 -->
          <PdfJsViewer :pdfSrc="pdfUrl" :isBase64="true" />
<!---->

<!--          <iframe :src="`/pdfjs/web/viewer.html?file=${encodeURIComponent(pdfUrl)}`" width="100%" height="100%"></iframe>-->
        </div>
      </div>
    </div>

    <!-- 内容区域 -->
    <div class="content-area" v-if="!showPdf">
      <div v-if="!selectedSubMenu" class="empty-content">
        <i class="el-icon-menu"></i>
        <p>请选择菜单项查看内容</p>
      </div>
      <div v-else class="selected-content">
        <h3>{{ currentSubMenu.title }}</h3>
        <div class="content-details">
          <p><strong>ID:</strong> {{ currentSubMenu.cataLogId }}</p>
          <p><strong>分类:</strong> {{ currentSubMenu.category }}</p>
        </div>
        <button class="view-pdf-btn" @click="loadPdf">
          <i class="el-icon-view"></i>
          查看PDF
        </button>
      </div>
    </div>
  </div>
</template>

<script>

import  PdfJsViewer from '../../components/PdfVue.vue'
export default {
  name: 'MobileMenuPage',
  components: {
    PdfJsViewer  // 注册组件
  },
  data() {
    return {
      selectedMenu: null, // 默认不选中任何菜单
      selectedSubMenu: null,
      showPdf: false,
      loading: false,
      pdfError: null,
      pdfUrl: null,
      iframeLoaded: false,
      // 模拟后端接口返回的数据
      menuData: [
        {
          docId: 1,
          title: '技术文档',
          parentId: 0,
          children: [
            {
              cataLogId: '11',
              title: 'Vue.js开发指南',
              parentId: 1
            },
            {
              cataLogId: '2',
              title: 'ElementUI使用手册',
              parentId: 1
            },
            {
              cataLogId: '3',
              title: '移动端适配方案',
              parentId: 1
            }
          ]
        },
        {
          docId: 2,
          title: '产品文档',
          parentId: 0,
          children: [
            {
              cataLogId: '4',
              title: '产品需求文档',
              parentId: 2
            },
            {
              cataLogId: '5',
              title: '用户手册',
              parentId: 2
            },
            {
              cataLogId: '6',
              title: 'API接口文档',
              parentId: 2
            }
          ]
        },
        {
          docId: 3,
          title: '项目文档',
          parentId: 0,
          children: [
            {
              cataLogId: '7',
              title: '项目计划书',
              parentId: 3
            },
            {
              cataLogId: '8',
              title: '项目总结报告',
              parentId: 3
            },
            {
              cataLogId: '9',
              title: '技术架构文档',
              parentId: 3
            }
          ]
        },
        {
          docId: 4,
          title: '学习资源',
          parentId: 0,
          children: [
            {
              cataLogId: '10',
              title: '视频教程',
              parentId: 4
            },
            {
              cataLogId: '11',
              title: '在线课程',
              parentId: 4
            },
            {
              cataLogId: '12',
              title: '实践项目',
              parentId: 4
            }
          ]
        }
      ]
    }
  },
  computed: {
    // 处理菜单数据，添加固定的样式属性
    processedMenuList() {
      return this.menuData.map(menu => ({
        ...menu,
        icon: 'el-icon-folder', // 固定一级菜单图标
        expanded: false, // 默认不展开
        children: menu.children.map(child => ({
          ...child,
          icon: 'el-icon-document', // 固定二级菜单图标
          category: this.getCategory(child.title) // 根据标题生成分类
        }))
      }))
    },
    currentSubMenu() {
      if (!this.selectedSubMenu) return null

      for (const menu of this.processedMenuList) {
        const found = menu.children.find(item => item.cataLogId === this.selectedSubMenu)
        if (found) return found
      }
      return null
    }
  },
  methods: {
    onPdfLoad() {
      this.iframeLoaded = true
    },
    onPdfError(event) {
      this.pdfError = `加载PDF失败，错误码: ${event.target.error.code}`
    },
    // 根据标题生成分类
    getCategory(title) {
      const categories = {
        'Vue.js开发指南': '前端开发',
        'ElementUI使用手册': 'UI组件',
        '移动端适配方案': '移动开发',
        '产品需求文档': '产品管理',
        '用户手册': '用户支持',
        'API接口文档': '后端开发',
        '项目计划书': '项目管理',
        '项目总结报告': '项目总结',
        '技术架构文档': '架构设计',
        '视频教程': '视频学习',
        '在线课程': '在线教育',
        '实践项目': '项目实践'
      }
      return categories[title] || '其他'
    },

    // 切换菜单展开状态
    toggleMenu(index) {
      // 关闭其他菜单
      this.processedMenuList.forEach((menu, i) => {
        if (i !== index) {
          menu.expanded = false
        }
      })

      // 切换当前菜单
      this.processedMenuList[index].expanded = !this.processedMenuList[index].expanded
      this.selectedMenu = index

      // 如果关闭菜单，清除选中的子菜单
      if (!this.processedMenuList[index].expanded) {
        this.selectedSubMenu = null
        this.closePdf()
      }
    },

    // 选择二级菜单
    async selectSubMenu(subItem) {
      this.selectedSubMenu = subItem.cataLogId
      console.log('选择了:', subItem.title, 'ID:', subItem.cataLogId)

      // 自动加载PDF
      await this.loadPdf()
    },

    // 加载PDF
    async loadPdf() {
      if (!this.currentSubMenu) return

      this.loading = true
      this.pdfError = null
      this.showPdf = true

      try {
        // 调用后端接口获取PDF数据
        const response = await this.fetchPdfData(this.currentSubMenu.cataLogId)

        if (response.success) {
          // 处理PDF数据
          // this.pdfUrl = this.processPdfData(response.data)
          console.log("base64:"+response.data.data)
          this.pdfUrl = response.data.data;

        } else {
          throw new Error(response.message || '获取PDF失败')
        }
      } catch (error) {
        console.error('加载PDF失败:', error)
        this.pdfError = error.message || '加载PDF失败，请重试'
      } finally {
        this.loading = false
      }


/*      try {

        this.pdfUrl = '/pdf/java.pdf';

      } catch (error) {
        console.error('加载PDF失败:', error)
        this.pdfError = error.message || '加载PDF失败，请重试'
      } finally {
        this.loading = false
      }*/



    },

    // 调用后端接口获取PDF数据
    async fetchPdfData(cataLogId) {
      // 模拟API调用
/*      return new Promise((resolve, reject) => {
        setTimeout(() => {
          // 模拟不同的PDF数据
          const pdfData = {
            '11': {
              type: 'url',
              url: 'https://mozilla.github.io/pdf.js/web/compressed.tracemonkey-pldi-09.pdf'
            },
            '2': {
              type: 'base64',
              data: 'JVBERi0xLjQKJcOkw7zDtsO...' // 模拟base64数据
            },
            '3': {
              type: 'url',
              url: 'https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf'
            },
            '4': {
              type: 'url',
              url: 'https://www.africau.edu/images/default/sample.pdf'
            },
            '5': {
              type: 'url',
              url: 'https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf'
            },
            '6': {
              type: 'url',
              url: 'https://mozilla.github.io/pdf.js/web/compressed.tracemonkey-pldi-09.pdf'
            }
          }

          const data = pdfData[cataLogId]

          if (data) {
            resolve({
              success: true,
              data: data
            })
          } else {
            resolve({
              success: false,
              message: 'PDF文件不存在'
            })
          }
        }, 1000) // 模拟网络延迟
      })*/

      // 实际使用时替换为真实的API调用
      try {
     /*   const response = await this.$http.get(`/api/pdf/${cataLogId}`)
        return response.data*/

        // 使用fetch API调用后端接口
        const response = await fetch(`http://localhost:8089/api/pdf/base64/${cataLogId}`)
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`)
        }
        const data = await response.json()
        console.log(data)
        return data


      } catch (error) {
        throw error
      }
    },

    // 处理PDF数据
    processPdfData(data) {
      if (data.type === 'url') {
        return data.url
      } else if (data.type === 'base64') {
        // 将base64数据转换为blob URL
        const byteCharacters = atob(data.data)
        const byteNumbers = new Array(byteCharacters.length)
        for (let i = 0; i < byteCharacters.length; i++) {
          byteNumbers[i] = byteCharacters.charCodeAt(i)
        }
        const byteArray = new Uint8Array(byteNumbers)
        const blob = new Blob([byteArray], { type: 'application/pdf' })
        return URL.createObjectURL(blob)
      }
      return null
    },

    // 关闭PDF预览
    closePdf() {
      this.showPdf = false
      this.pdfUrl = null
      this.pdfError = null
      this.loading = false
    },

    // 模拟从后端获取菜单数据
    async fetchMenuData() {
      try {
        // 这里应该是实际的API调用
        // const response = await this.$http.get('/api/menu')
        // this.menuData = response.data

        // 目前使用模拟数据
        console.log('菜单数据加载完成')
      } catch (error) {
        console.error('获取菜单数据失败:', error)
      }
    }
  },
  mounted() {
    // 页面加载时获取菜单数据
    this.fetchMenuData()
  },
  beforeDestroy() {
    // 清理blob URL
    if (this.pdfUrl && this.pdfUrl.startsWith('blob:')) {
      URL.revokeObjectURL(this.pdfUrl)
    }
  }
}
</script>

<style scoped>
/* 全局样式 */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.mobile-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  font-family: 'Helvetica Neue', Helvetica, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', '微软雅黑', Arial, sans-serif;
}

/* 头部样式 */
.header {
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  padding: 1rem;
  text-align: center;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.header h1 {
  color: white;
  font-size: 1.5rem;
  font-weight: 500;
  margin: 0;
}

/* 菜单容器 */
.menu-container {
  padding: 1rem;
  max-width: 600px;
  margin: 0 auto;
}

.menu-item {
  margin-bottom: 0.5rem;
  background: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.menu-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.15);
}

/* 一级菜单 */
.menu-level-1 {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 1rem;
  cursor: pointer;
  transition: all 0.3s ease;
  background: white;
}

.menu-level-1:hover {
  background: #f8f9fa;
}

.menu-level-1.active {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.menu-content {
  display: flex;
  align-items: center;
  flex: 1;
}

.menu-icon {
  font-size: 1.2rem;
  margin-right: 0.75rem;
  color: #667eea;
}

.menu-level-1.active .menu-icon {
  color: white;
}

.menu-title {
  font-size: 1rem;
  font-weight: 500;
}

.arrow-icon {
  font-size: 1rem;
  transition: transform 0.3s ease;
  color: #909399;
}

.menu-level-1.active .arrow-icon {
  color: white;
}

.arrow-icon.rotated {
  transform: rotate(180deg);
}

/* 二级菜单 */
.submenu {
  background: #f8f9fa;
  border-top: 1px solid #e9ecef;
}

.menu-level-2 {
  display: flex;
  align-items: center;
  padding: 1rem;
  cursor: pointer;
  transition: all 0.3s ease;
  border-bottom: 1px solid #e9ecef;
  position: relative;
}

.menu-level-2:last-child {
  border-bottom: none;
}

.menu-level-2:hover {
  background: #e9ecef;
}

.menu-level-2.active {
  background: #e3f2fd;
  border-left: 4px solid #2196f3;
}

.submenu-icon {
  font-size: 1rem;
  margin-right: 0.75rem;
  color: #667eea;
  width: 20px;
  text-align: center;
}

.submenu-title {
  font-size: 0.9rem;
  font-weight: 500;
  color: #333;
}

/* 子菜单动画 */
.submenu-enter-active, .submenu-leave-active {
  transition: all 0.3s ease;
  max-height: 300px;
  overflow: hidden;
}

.submenu-enter, .submenu-leave-to {
  max-height: 0;
  opacity: 0;
}

/* PDF预览区域 */
.pdf-container {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: white;
  z-index: 1000;
  display: flex;
  flex-direction: column;
}

.pdf-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 1rem;
  background: #f8f9fa;
  border-bottom: 1px solid #e9ecef;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.pdf-header h3 {
  margin: 0;
  color: #333;
  font-size: 1.1rem;
}

.close-btn {
  background: none;
  border: none;
  font-size: 1.2rem;
  color: #666;
  cursor: pointer;
  padding: 0.5rem;
  border-radius: 4px;
  transition: all 0.3s ease;
}

.close-btn:hover {
  background: #e9ecef;
  color: #333;
}

.pdf-content {
  flex: 1;
  position: relative;
  overflow: hidden;
}

.loading, .error {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #666;
}

.loading i {
  font-size: 2rem;
  margin-bottom: 1rem;
  animation: spin 1s linear infinite;
}

.error i {
  font-size: 2rem;
  margin-bottom: 1rem;
  color: #f56c6c;
}

.retry-btn {
  margin-top: 1rem;
  padding: 0.5rem 1rem;
  background: #409eff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.retry-btn:hover {
  background: #337ecc;
}

.pdf-viewer {
  height: 100%;
  width: 100%;
}

.pdf-viewer iframe {
  border: none;
  width: 100%;
  height: 100%;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

/* 内容区域 */
.content-area {
  padding: 1rem;
  max-width: 600px;
  margin: 0 auto;
}

.empty-content {
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(10px);
  border-radius: 12px;
  padding: 2rem;
  text-align: center;
  color: #666;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
}

.empty-content i {
  font-size: 3rem;
  color: #ddd;
  margin-bottom: 1rem;
  display: block;
}

.empty-content p {
  font-size: 1rem;
  margin: 0;
}

.selected-content {
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(10px);
  border-radius: 12px;
  padding: 1.5rem;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
  animation: slideIn 0.3s ease;
}

.selected-content h3 {
  color: #333;
  font-size: 1.2rem;
  margin-bottom: 0.5rem;
  font-weight: 500;
}

.content-details {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 1rem;
  margin-bottom: 1rem;
}

.content-details p {
  margin: 0.25rem 0;
  font-size: 0.85rem;
}

.content-details strong {
  color: #333;
}

.view-pdf-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  padding: 0.75rem;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 1rem;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);
}

.view-pdf-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.6);
}

.view-pdf-btn i {
  margin-right: 0.5rem;
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 移动端优化 */
@media screen and (max-width: 768px) {
  .menu-container {
    padding: 0.5rem;
  }

  .content-area {
    padding: 0.5rem;
  }

  .header h1 {
    font-size: 1.3rem;
  }

  .menu-level-1 {
    padding: 0.875rem;
  }

  .menu-level-2 {
    padding: 0.875rem;
  }

  .selected-content {
    padding: 1rem;
  }

  .pdf-header {
    padding: 0.75rem;
  }

  .pdf-header h3 {
    font-size: 1rem;
  }
}

/* 触摸优化 */
* {
  -webkit-tap-highlight-color: transparent;
  -webkit-touch-callout: none;
  -webkit-user-select: none;
  user-select: none;
}

.menu-level-1, .menu-level-2, .close-btn, .retry-btn, .view-pdf-btn {
  -webkit-tap-highlight-color: rgba(0, 0, 0, 0.1);
}

/* 滚动条样式 */
::-webkit-scrollbar {
  width: 4px;
}

::-webkit-scrollbar-track {
  background: transparent;
}

::-webkit-scrollbar-thumb {
  background: rgba(255, 255, 255, 0.3);
  border-radius: 2px;
}

::-webkit-scrollbar-thumb:hover {
  background: rgba(255, 255, 255, 0.5);
}

/* 字体优化 */
body {
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

/* 响应式字体 */
@media screen and (max-width: 480px) {
  .menu-title {
    font-size: 0.9rem;
  }

  .submenu-title {
    font-size: 0.85rem;
  }
}
</style>